package com.jhws.sys.cms.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSON;
import com.jhws.business.aliyun.service.OSSClientService;
import com.jhws.business.customer.bo.CustomContentInfo;
import com.jhws.common.base.bo.Global;
import com.jhws.sys.user.bo.TblUserDimBo;
import com.jhws.sys.user.service.ITblUserDimService;
import com.jhws.sys.cms.bo.ResourceCustomType;
import com.jhws.sys.cms.bo.ResourceSort;
import com.jhws.sys.cms.bo.ResourceType;
import com.jhws.util.ObjectUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.WebUtils;

import com.google.common.collect.Lists;
import com.jhws.util.GetId;
import com.jhws.common.Page;
import com.jhws.core.db.BaseDao;
import com.jhws.core.exception.BizException;
import com.jhws.sys.cms.dao.ResourceDao;

@SuppressWarnings({"SqlDialectInspection", "Duplicates"})
@Service
public class ResourceService {
    public static final String ICON_PATH = "/temp/cms/";
    @Resource
    private ResourceDao rdao;
    @Resource
    private BaseDao BaseDao;
    @Resource
    protected ITblUserDimService IUserService;
    @Resource
    private CmsRedisService redisService;
    @Resource
    private OSSClientService ossClientService;

    /**
     * 保存资源类型
     *
     * @param rt 资源类型
     * @return 资源类型code
     */
    @SuppressWarnings("unchecked")
    public String saveType(ResourceType rt) {
        if (StringUtils.isNotBlank(rt.getType_id())) {
            if (StringUtils.equals(rt.getType_code(), rt.getParent_code())) {
                throw new BizException("父节点不能选择自身！");
            }
            List<ResourceType> result = BaseDao.findList("from ResourceType where type_id = '" + rt.getType_id() + "'");
            if (result.size() == 1) {
                //修改类型后子类型也要修改
                rdao.j().update("UPDATE cms_resource_type SET parent_code = '" + rt.getType_code() + "' WHERE parent_code = '" + result.get(0).getType_code() + "'");
                //修改类型后cms中的类型也要修改
                rdao.j().update("UPDATE cms_resource SET type_code = '" + rt.getType_code() + "' WHERE type_code = '" + result.get(0).getType_code() + "'");
                BaseDao.merge(rt);
            } else {
                throw new BizException("数据错误！");
            }
        } else {
            List result = rdao.j().queryForList("select 1 from cms_resource_type where type_code = ?", rt.getType_code());
            if (result.size() > 0) {
                throw new BizException("分类编码已经存在！");
            }
            rt.setType_id(GetId.randomID());
            rt.setCreate_time(new Date());
            rt.setCreator("");
            rdao.h().save(rt);
        }
        //只要节点发生改变，清空一下缓存
        redisService.emptyRedisCMSAll();
        return rt.getType_code();
    }

    /**
     * 查询所有标签类型，包括子标签类型
     *
     * @return
     */
    public List<Map<String, Object>> queryTypes(String parentCode) {
        List<Map<String, Object>> orgin = rdao.queryTypes(parentCode);
        List<Map<String, Object>> types = Lists.newArrayList();
        for (Map<String, Object> o : orgin) {
            String typeName = MapUtils.getString(o, "type_name");
            typeName = StringUtils.isEmpty(typeName) ? MapUtils.getString(o, "description") : typeName;
            o.put("name", typeName);

            String customProperty = MapUtils.getString(o, "customProperty");
            if (StringUtils.isNotEmpty(customProperty)) {
                List<CustomContentInfo> customPropertyInfos = JSON.parseArray(customProperty, CustomContentInfo.class);
                o.put("customProperty", customPropertyInfos);
            }

            setChildren(o, orgin);
            if ("-1".equals(MapUtils.getString(o, "parent_code"))
                    || (!StringUtils.isEmpty(parentCode) && parentCode.equals(MapUtils.getString(o, "parent_code")))) {
                types.add(o);
            }
        }
        return types;
    }

    /**
     * 条件查询类型
     *
     * @param where 条件
     * @return
     */
    public List<ResourceType> queryTypesByWhere(String where) {
        return BaseDao.findList("from ResourceType " + where);
    }

    /**
     * 组合子标签
     *
     * @param father
     * @param orgin
     */
    private void setChildren(Map<String, Object> father, List<Map<String, Object>> orgin) {
        List<Map<String, Object>> son = Lists.newArrayList();
        for (Map<String, Object> o : orgin) {
            String fid = MapUtils.getString(father, "type_code");
            if (StringUtils.equals(fid, MapUtils.getString(o, "parent_code"))) {
                o.put("parent_name", father.get("type_name"));
                o.put("parent_code", fid);
                son.add(o);
                setChildren(o, orgin);
            }
        }
        if (son.size() > 0) {
            father.put("children", son);
        }
    }

    /**
     * 删除类型
     *
     * @param rt 类型ID
     */
    public void deleteType(ResourceType rt) {
        if (StringUtils.isBlank(rt.getType_id())) {
            throw new BizException("-1", "", "请选择需要删除的分类信息");
        }
        List result = rdao.j().queryForList("select 1 from cms_resource_type where parent_code = ?", rt.getType_code());
        if (result.size() > 0) {
            throw new BizException("-1", "", "该分类信息下存在子分类，请先删除子分类！");
        }

        rdao.j().update("delete from cms_resource where type_code = ?", rt.getType_code());
        rdao.h().delete(rt);
    }

    /**
     * 保存自定义类型
     *
     * @param customType 自定义类型
     * @return
     */
    public String saveResourceCustomType(ResourceCustomType customType) {
        if (StringUtils.isNotBlank(customType.getCustomTypeId())) {
            BaseDao.saveOrUpdate(customType);
        } else {
            List result = rdao.j().queryForList("select 1 from cms_resource_custom_type where custom_type_code = ?", customType.getCustomTypeCode());
            if (result.size() > 0) {
                throw new BizException("分类编码已经存在！");
            }
            rdao.h().save(customType);
        }
        return customType.getCustomTypeId();
    }

    /**
     * 查询自定义类型
     *
     * @param param sortCode
     * @return
     * @throws Exception
     */
    public Map<String, Object> queryResourceCustomType(Map param) throws Exception {
        boolean isPage = MapUtils.getBooleanValue(param, "isPage");
        String customTypeId = MapUtils.getString(param, "customTypeId");
        String type = MapUtils.getString(param, "type");
        boolean isAnalysisCustomContent = MapUtils.getBooleanValue(param, "isAnalysisCustomContent");
        String sql = "SELECT\n" + "	a.custom_type_id,\n" + "	a.custom_type_code,\n"
                + "	a.custom_type_name,\n" + "	a.custom_content,\n" + "	a.description\n"
                + " FROM cms_resource_custom_type a" + " WHERE 1=1 ";
        if (StringUtils.isNotEmpty(customTypeId)) {
            sql += "and custom_type_id in (" + com.jhws.util.StringUtils.spilt(customTypeId) + ")";
        }
        if (StringUtils.isNotEmpty(type)) {
            sql += "and type = '" + type + "'";
        }
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> list;
        if (isPage) {
            Page p = rdao.queryPage(sql, Map.class);
            list = p.getList();
            result.put("size", p.getTotalNumber());
        } else {
            list = rdao.j().queryForList(sql);
        }
        if (isAnalysisCustomContent) {
            for (Map<String, Object> o : list) {
                String customContent = MapUtils.getString(o, "custom_content");
                if (StringUtils.isNotEmpty(customContent)) {
                    List<CustomContentInfo> customContentInfos = JSON.parseArray(customContent, CustomContentInfo.class);
                    for (CustomContentInfo customContentInfo : customContentInfos) {
                        if (Global.CMS_CUSTOM_SORT.equals(customContentInfo.getCustomType())) {
                            param = new HashMap();
                            param.put("isPage", false);
                            param.put("sortCode", true);

                            queryResourceSortPage(param);
                        }
                    }
                    o.put("customContents", customContentInfos);
                }
            }
        }
        result.put("list", list);
        return result;
    }

    /**
     * 删除自定义类型
     *
     * @param customType
     */
    public void deleteCustomType(ResourceCustomType customType) {
        if (StringUtils.isBlank(customType.getCustomTypeId())) {
            throw new BizException("-1", "", "请选择需要删除的分类信息");
        }
        rdao.h().delete(customType);
    }

    /**
     * 查询资源列表
     *
     * @param includeSub 是否查子类？
     * @param param      （type_id，type_name）
     * @return
     * @throws IOException
     */
    public Map<String, Object> queryResourcePage(boolean includeSub, Map param) throws IOException {
        TblUserDimBo userBo = IUserService.currentUser();
        String typeCode = MapUtils.getString(param, "type_code", "");
        //是否查询默认小区数据
        boolean isDefQueryResource = MapUtils.getBooleanValue(param, "isDefQueryResource");
        String typeIdCondition = includeSub(includeSub, typeCode);
        String sql = "SELECT\n" + "	a.resource_id,\n" + "	b.type_name,\n" + "	a.title,\n" + "	a.icon_url,\n"
                + "	a.content_url,\n" + "	a.create_time,\n" + "	a.creator,\n" + "	a.type_code,\n"
                + "	a.isApproved,\n" + "	a.approvedState,\n" + "	a.comm_code,\n" + "	a.description\n" + "FROM\n"
                + "	cms_resource a,\n" + "	cms_resource_type b\n" + "WHERE\n" + "	a.type_code = b.type_code ";

        String isApproved = MapUtils.getString(param, "isApproved", "");
        if (!StringUtils.isEmpty(isApproved)) {
            sql += " and a.isApproved = '" + isApproved + "' ";
        }

        //查询只能是当前帐号录制的资源，对默认小区特殊处理
        String commCode = MapUtils.getString(param, "commCode", "");
        if (!SecurityUtils.getSubject().hasRole(Global.ROLE_SUPPER_ADMIN) || !Global.CMS_IS_APPROVED.equals(isApproved)) {
            if (StringUtils.isEmpty(commCode) && isDefQueryResource && !Global.DEFAULT_COMM.equals(userBo.getCommCode())) {
                sql += " and ((a.creator = '" + userBo.getLogName() + "' and a.comm_code is null) or a.comm_code = '" + Global.DEFAULT_COMM + "')";
            } else if (StringUtils.isEmpty(commCode)) {
                sql += " and a.comm_code is null and a.creator = '" + userBo.getLogName() + "'";
            } else {
                sql += " and a.comm_code = '" + commCode + "'";
            }
        }
        sql += typeIdCondition;
        sql += " order by a.create_time desc";
        Map<String, Object> result = new HashMap<>();
        Page p = rdao.queryPage(sql, Map.class);
        List<Map<String, Object>> list = p.getList();
        for (Map<String, Object> map : list) {
            String objUrl = (String) map.get("icon_url");
            String url = ossClientService.getUrl(objUrl, false);
            if (!StringUtils.isEmpty(url) && !url.equals(objUrl)) {
                map.replace("icon_url", url);
            }
        }
        result.put("list", list);
        result.put("size", p.getTotalNumber());
        return result;
    }

    /**
     * 查询资源列表
     *
     * @param includeSub 是否查子类？
     * @param typeCode   （typeCode）
     * @return
     * @throws IOException
     */
    public List<Map<String, Object>> queryResourceList(boolean includeSub, String typeCode, String date, String commCode) throws IOException {
        String typeIdCondition = includeSub(includeSub, typeCode);
        String sql = "SELECT\n" + "	b.type_name,\n" + "	a.resource_id,\n" + "	a.title,\n" + "	a.icon_url,\n"
                + "	a.content_url,\n" + " a.type_code,\n" + " a.description,\n" + "	a.isApproved,\n" + " a.customContent,\n" + " a.create_time\n" + " FROM\n"
                + "	cms_resource a,\n" + "	cms_resource_type b\n" + "WHERE\n" + "	a.type_code = b.type_code ";

        sql += " and a.isApproved = '" + Global.CMS_APPROVED + "' ";
        if (!StringUtils.isEmpty(commCode)) {
            sql += " and a.comm_code = '" + commCode + "'";
        }
        //增量查询
        if (date != null) {
            sql += " and a.create_time > '" + date + "'";
        }
        sql += typeIdCondition;
        sql += " order by create_time desc";

        List<Map<String, Object>> list = rdao.j().queryForList(sql);
        for (Map<String, Object> map : list) {
            String objUrl = (String) map.get("icon_url");
            String url = ossClientService.getUrl(objUrl, false);
            if (!StringUtils.isEmpty(url) && !url.equals(objUrl)) {
                map.replace("icon_url", url);
            }
        }
        return list;
    }

    /**
     * 查询资源列表api返回数据使用
     *
     * @param typeCode （typeCode）
     * @return
     * @throws IOException
     */
    public List<Map<String, Object>> queryResourceListApi(String typeCode, String commCode) throws IOException {
        List<Map<String, Object>> resourceList = new ArrayList<>();
        List<Map<String, Object>> resourceListTerr = queryResourceRecursions(typeCode, commCode, resourceList);
        if (resourceList.size() == 0 && !Global.DEFAULT_COMM.equals(commCode))
            resourceListTerr = queryResourceRecursions(typeCode, Global.DEFAULT_COMM, resourceList);
        return resourceListTerr;
    }

    /**
     * @param typeCode     资源code
     * @param commCode     小区
     * @param resourceList 父标签下所以资源
     * @return
     * @throws IOException
     */
    private List<Map<String, Object>> queryResourceRecursions(String typeCode, String commCode, List<Map<String, Object>> resourceList) throws IOException {
        String hql = "from ResourceType where 1=1 and parent_code='" + typeCode + "'";
        List<ResourceType> resourceTypes = BaseDao.findList(hql);
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (ResourceType resourceType : resourceTypes) {
            Map<String, Object> types = new HashedMap();
            List<Map<String, Object>> tempMap = queryResourceRecursions(resourceType.getType_code(), commCode, resourceList);

            String sql = "SELECT\n" + "	a.title,\n" + "	a.icon_url,\n"
                    + "	a.content_url,\n" + " a.description,\n" + " a.customType,\n" + " a.customContent\n" + " FROM\n"
                    + "	cms_resource a\n" + " WHERE a.type_code ='" + resourceType.getType_code() + "'";
            if (!StringUtils.isEmpty(commCode)) {
                sql += " and a.comm_code = '" + commCode + "'";
            }
            List<Map<String, Object>> list = rdao.j().queryForList(sql);
            for (Map<String, Object> map : list) {
                String objUrl = (String) map.get("icon_url");
                String url = ossClientService.getUrl(objUrl, false);
                if (!StringUtils.isEmpty(url) && !url.equals(objUrl)) {
                    map.replace("icon_url", url);
                }
            }

            int nodeSize = tempMap.size();
            if (list.size() > 0) {
                for (Map<String, Object> o : list) {
                    String customContent = MapUtils.getString(o, "customContent");
                    if (!org.apache.commons.lang.StringUtils.isEmpty(customContent)) {
                        List<CustomContentInfo> customContentInfos = JSON.parseArray(customContent, CustomContentInfo.class);
                        o.put("customContent", customContentInfos);
                    }
                }
                types.put("type", resourceType.getType_code());
                types.put("resource", list);
                resourceList.addAll(list);
            } else if (nodeSize <= 0) {
                continue;
            }
            if (nodeSize > 0) {
                types.put("type", resourceType.getType_code());
                types.put("node", tempMap);
            }
            types.put("typeName", resourceType.getType_name());

            if (StringUtils.isNotEmpty(resourceType.getCustomProperty())) {
                List<CustomContentInfo> customPropertyInfos = JSON.parseArray(resourceType.getCustomProperty(), CustomContentInfo.class);
                for (CustomContentInfo customContentInfo : customPropertyInfos) {
                    types.put(customContentInfo.getCustomKey(), customContentInfo.getCustomValue());
                }
            }

            mapList.add(types);
        }
        return mapList;
    }

    /**
     * 条件查询资源
     *
     * @param where 条件
     * @return
     */
    public List<com.jhws.sys.cms.bo.Resource> queryResourceList(String where) {
        return BaseDao.findList("from Resource " + where);
    }

    /**
     * @param ResourceId 资源ID
     * @return 资源
     */
    public com.jhws.sys.cms.bo.Resource queryResourceIdByResource(String ResourceId) {
        if (StringUtils.isEmpty(ResourceId)) {
            return null;
        }
        return BaseDao.get(com.jhws.sys.cms.bo.Resource.class, ResourceId);
    }

    /**
     * 拷贝更新资源
     *
     * @param resourceIds 去掉的资源ID
     * @param commCode    小区code
     * @throws Exception
     */
    public void updateResource(String typeCode, String[] resourceIds, String commCode) throws Exception {
        TblUserDimBo userBo = IUserService.currentUser();
        String sql = "select resource_id from cms_resource where 1=1 and isApproved = '" + Global.CMS_APPROVED + "'";

        if (StringUtils.isNotEmpty(typeCode)) {
            sql += " and type_code='" + typeCode + "'";
        }

        //默认小区特殊处理
        if (!Global.DEFAULT_COMM.equals(userBo.getCommCode()) && !Global.DEFAULT_COMM.equals(commCode)) {
            sql += " and ((creator = '" + userBo.getLogName() + "' and comm_code is null) or comm_code = '" + Global.DEFAULT_COMM + "') ";
        } else {
            sql += " and creator = '" + userBo.getLogName() + "' and comm_code is null";
        }

        String sqlTemp = "";
        if (resourceIds != null && resourceIds.length > 0) {
            for (String resourceId : resourceIds) {
                if (StringUtils.isEmpty(sqlTemp)) {
                    sqlTemp = " and resource_id not in('" + resourceId + "'";
                } else {
                    sqlTemp += ",'" + resourceId + "'";
                }
            }
            sqlTemp += ")";
        }
        sql += sqlTemp;
        List<String> resourceIdList = rdao.j().queryForList(sql, String.class);
        if (resourceIdList != null && resourceIdList.size() > 0) {
            for (String resourceId : resourceIdList) {
                sql = "insert into cms_resource(resource_id,content_url,create_time,description," +
                        "icon_url,title,creator,comm_code,type_code,isApproved, customType,customContent)"
                        + " select '" + GetId.GetId2()
                        + "' as resource_id,content_url,create_time,description,icon_url,title,creator, '" + commCode
                        + "' as comm_code,type_code,isApproved, customType,customContent " + " from cms_resource where resource_id='" + resourceId + "'";
                rdao.j().execute(sql);
            }
        }
    }

    /**
     * 拷贝更新资源
     *
     * @param resourceIds 选中的资源ID
     * @param ommGroupId  小区组ID
     * @throws Exception
     */
    public void updateResource(String[] resourceIds, String ommGroupId) throws Exception {
        if (resourceIds != null && resourceIds.length > 0) {
            for (String resourceId : resourceIds) {
                String sql = "insert into cms_resource(resource_id,content_url,create_time,description,"
                        + "icon_url,title,creator,type_code,isApproved, customType,customContent,parentResourceId,commGroupId)"
                        + " select '" + GetId.GetId2() + "' as resource_id,content_url,create_time,description,icon_url,title,creator, "
                        + " type_code,isApproved, customType,customContent,resource_id,'" + ommGroupId + "' as commGroupId"
                        + " from cms_resource where resource_id='" + resourceId + "'";
                rdao.j().execute(sql);
            }
        }
    }

    /**
     * @param includeSub true 父节点开始查询
     * @param typeCode   资源类型
     * @return
     */
    private String includeSub(boolean includeSub, String typeCode) {
        String typeIdCondition = "";
        if (StringUtils.isNotBlank(typeCode)) {
            if (includeSub) {
                List<String> subTypeIds = new ArrayList<>();
                queryChildCode(subTypeIds, typeCode);
                if (CollectionUtils.isNotEmpty(subTypeIds)) {
                    typeIdCondition = " and a.type_code in ('" + typeCode + "'";
                    for (String id : subTypeIds) {
                        typeIdCondition += ",'" + id + "'";
                    }
                    typeIdCondition += ") ";
                } else {
                    typeIdCondition = " and a.type_code = '" + typeCode + "' ";
                }
            } else {
                typeIdCondition = " and a.type_code = '" + typeCode + "' ";
            }
        }
        return typeIdCondition;
    }

    //递归查询子类
    private void queryChildCode(List<String> typeCodes, String parentCode) {
        List<String> subTypeIds = rdao.j().queryForList(
                "select type_code from cms_resource_type where parent_code = ?", String.class, parentCode);
        if (CollectionUtils.isNotEmpty(subTypeIds)) {
            typeCodes.addAll(subTypeIds);
            for (String typeCode : subTypeIds) {
                queryChildCode(typeCodes, typeCode);
            }
        }
    }

    /**
     * 上传文件到远程图片服务器
     *
     * @param file
     * @return
     * @throws IOException
     */
    public String uploadRemoteFile(MultipartFile file, String fileName, boolean isTemp) throws IOException {
        String suffix = FilenameUtils.getExtension(file.getOriginalFilename());
        if (fileName == null) {
            fileName = GetId.randomID();
        }
        String key;
        if (isTemp) {
            key = "temp_1day/" + fileName + "." + suffix;
        } else {
            key = "cms/file/" + fileName + "." + suffix;
        }
        ossClientService.updateFile(key, file.getInputStream());
        return key;// listObjectsOss.getUrl(key);
    }

    /**
     * 拷贝文件
     *
     * @param key
     * @param newFileName
     * @return
     * @throws IOException
     */
    public String copyRemoteFile(String key, String newFileName) throws IOException {
        String suffix = FilenameUtils.getExtension(key);
        String destKey = "cms/file/" + newFileName + "." + suffix;
        ossClientService.gerneralCopyFile(key, destKey);
        return destKey;// listObjectsOss.getUrl(key);
    }

    /**
     * 删除oss上的资源同时就要删除所有相应的资源记录
     *
     * @param key ossKey
     */
    public void deleteRemoteFile(String key) {
        ossClientService.deleteObject(key);
        String sql = "delete from cms_resource where icon_url = '" + key + "'";
        rdao.j().execute(sql);
    }

    /**
     * 根据路径直接得到图标内容
     *
     * @param path
     * @return
     * @throws IOException
     */
    public HttpEntity<byte[]> download(String path) throws IOException {
        String savePath = getSavePath(path);
        InputStream in = new FileInputStream(savePath);
        byte[] file = new byte[in.available()];
        IOUtils.read(in, file);
        HttpHeaders headers = new HttpHeaders();

        headers.setContentType(MediaType.IMAGE_JPEG);

        headers.setContentLength(file.length);
        HttpEntity<byte[]> en = new ResponseEntity<byte[]>(file, headers, HttpStatus.OK);
        return en;
    }

    private String getSavePath(String path) throws IOException {
        FileUtils.forceMkdir(new File(System.getProperty(WebUtils.DEFAULT_WEB_APP_ROOT_KEY) + ICON_PATH));
        return System.getProperty(WebUtils.DEFAULT_WEB_APP_ROOT_KEY) + ICON_PATH + path;
    }

    /**
     * 保存资源，如果有id，则更新
     *
     * @param r
     */
    public void saveResource(com.jhws.sys.cms.bo.Resource r) {
        if (StringUtils.isBlank(r.getResource_id())) {
            r.setResource_id(GetId.randomID());
            r.setCreate_time(new Date());
            rdao.h().save(r);
        } else {
            rdao.h().update(r);
        }
    }

    /**
     * 判断ResourceSortCode是否存在
     *
     * @param sortCode
     */
    @SuppressWarnings("SqlNoDataSourceInspection")
    public boolean isResourceSortCode(String sortCode) {
        List<String> sortIds = rdao.j().queryForList(
                "select sort_id from cms_resource_sort where sort_code = ?", String.class, sortCode);
        return sortIds != null && sortIds.size() > 0;
    }

    /**
     * 保存资源类型，如果有id，则更新
     *
     * @param rs
     */
    public ResourceSort saveResourceSort(ResourceSort rs) {
        if (StringUtils.isBlank(rs.getSortId())) {
            rdao.h().save(rs);
        } else {
            rdao.h().update(rs);
        }
        return rs;
    }

    /**
     * 查询资源类型列表
     *
     * @param param sortCode
     * @return
     * @throws Exception
     */
    public Map<String, Object> queryResourceSortPage(Map param) throws Exception {
        String sortCode = MapUtils.getString(param, "sortCode", "");
        boolean isPage = MapUtils.getBooleanValue(param, "isPage");
        if (StringUtils.isEmpty(sortCode)) {
            throw new BizException("类型编码不能为空！");
        }
        String sql = "SELECT\n" + "	a.sort_id,\n" + "	a.sort_code,\n" + "	a.sort_name,\n"
                + "	a.display_name,\n" + "	a.sort_value,\n" + "	a.description\n"
                + " FROM cms_resource_sort a" + " WHERE\n" + "	a.sort_code = '" + sortCode + "'";
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> list;
        if (isPage) {
            Page p = rdao.queryPage(sql, Map.class);
            list = p.getList();
            result.put("size", p.getTotalNumber());
        } else {
            list = rdao.j().queryForList(sql);
        }
        result.put("list", list);
        return result;
    }

    /**
     * 删除资源
     *
     * @param r
     */
    public void deleteResource(com.jhws.sys.cms.bo.Resource r) {
        rdao.h().delete(r);
    }

    /**
     * 删除类型
     *
     * @param rs
     */
    public void deleteResourceSort(ResourceSort rs) {
        if (rs.getSortId() != null) {
            rdao.h().delete(rs);
        } else if (rs.getSortCode() != null) {
            String sql = "delete from cms_resource_sort where 1=1 and sort_code = '" + rs.getSortCode() + "'";
            rdao.j().execute(sql);
        }
    }

    /**
     * 删除资源
     *
     * @param typeCode 资源类型code
     */
    public void deleteResource(String typeCode, String commCode) {
        String sql = "delete from cms_resource where 1=1 ";
        if (typeCode == null || commCode == null) {
            throw new BizException("删除条件错误！");
        }
        sql += " and type_code = '" + typeCode + "' and comm_code = '" + commCode + "'";
        rdao.j().execute(sql);
    }

    /**
     * 条件删除资源
     *
     * @param where 条件
     */
    public void deleteResource(String where) {
        String sql = "delete from cms_resource " + where;
        rdao.j().execute(sql);
    }

    /**
     * 获取标签类型的下拉列表树形结构
     *
     * @return
     */
    public List<Map<String, Object>> queryTypesTree(String parentCode) {
        List<Map<String, Object>> types = this.queryTypes(parentCode);
        List<Map<String, Object>> result = Lists.newLinkedList();
        tree(types, result, 0);
        return result;
    }

    /**
     * 组合树型类型
     *
     * @param types
     * @param result
     * @param depth
     */
    private void tree(List<Map<String, Object>> types, List<Map<String, Object>> result, int depth) {
        String prefix = "";
        for (int i = 0; i < depth; i++) {
            prefix += "--";
        }

        for (Map<String, Object> m : types) {
            String typeName = MapUtils.getString(m, "type_name");
            typeName = com.jhws.util.StringUtils.isEmpty(typeName) ? MapUtils.getString(m, "description") : typeName;
            m.put("type_name", prefix + typeName);
            result.add(m);
            List<Map<String, Object>> son = (List<Map<String, Object>>) MapUtils.getObject(m, "children");
            if (CollectionUtils.isNotEmpty(son)) {
                tree(son, result, depth + 1);
            }
        }
    }
}
